#include "tinyxml2.h"
#include <cfloat>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <regex>

using namespace tinyxml2;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::regex;

struct RssItem
{
    string title;
    string link;
    string description;
    string content;
};

class RssReader
{
public:
    RssReader();

    void parseRss();
    void dump(const string & filename);//输出
private:
    vector<RssItem> _rss;
};

void RssReader::parseRss()
{
    XMLDocument doc;
	doc.LoadFile( "coolshell.xml" );//加载文件
    if(doc.ErrorID())
    {
        std::cerr << "LoadFile error" << endl;
        return;
    }

    XMLElement* root = doc.FirstChildElement( "rss" )
        ->FirstChildElement("channel")
        ->FirstChildElement("item");

    while(root)
    {
        string title = root->FirstChildElement("title")->GetText();
        string link = root->FirstChildElement("link")->GetText();
        string des = root->FirstChildElement("description")->GetText();
        string content = root->FirstChildElement("content:encoded")->GetText();

        //正则表达式
        regex rgx("<[^>]+>");
        des = std::regex_replace(des, rgx, "");
        content = std::regex_replace(content, rgx, "");

        cout << "title = " << title << endl;
        cout << "link = " << link << endl;
        cout << "des  = " << des << endl;
        cout << "content = " << content << endl;

        RssItem rtem;
        rtem.title = title;
        rtem.link = link;
        rtem.description = des;
        rtem.content = content;

        _rss.push_back(rtem);

        root = root->NextSiblingElement("item");//获取兄弟节点
    }

}

void RssReader::dump(const string & filename)
{
    std::ofstream ofs(filename);

    for(size_t idx = 0; idx != _rss.size(); ++idx)
    {
        ofs << "<doc><docid>" << idx + 1 
            << "</docid><title>"<< _rss[idx].title 
            << "</title><link>" << _rss[idx].link
            << "</link><description>" << _rss[idx].description
            << "</description><content>" << _rss[idx].content
            << "</content></doc>" << endl;
    }
}

int main(int argc, char *argv[])
{
    return 0;
}

